package net.qunzhi.modules.weixin.config;

import net.qunzhi.modules.weixin.handler.LogHandler;
import net.qunzhi.modules.weixin.handler.SubscribeHandler;
import net.qunzhi.modules.weixin.handler.UnsubscribeHandler;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.stream.Collectors;

import static me.chanjar.weixin.common.api.WxConsts.EventType.SUBSCRIBE;
import static me.chanjar.weixin.common.api.WxConsts.EventType.UNSUBSCRIBE;
import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType.EVENT;

/**
 * 微信SDK（WxJava）配置类
 * Created by lsd
 * 2019-07-26 09:16
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(WxMpProperties.class)
public class WechatMpConfig {

    @Autowired
    private WxMpProperties wxMpProperties;
    @Autowired
    private SubscribeHandler subscribeHandler;
    @Autowired
    private UnsubscribeHandler unsubscribeHandler;
    @Autowired
    private LogHandler logHandler;

    /**
     * 注入 wxMpService
     */
    @Bean
    public WxMpService wxMpService() {
        final List<WxMpProperties.MpConfig> configs = wxMpProperties.getConfigs();
        if (configs == null) {
            throw new RuntimeException("添加下相关配置，注意别配错了！");
        }
        WxMpServiceImpl wxMpService = new WxMpServiceImpl();
        wxMpService.setMultiConfigStorages(configs
                .stream().map(a -> {
                    WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl();
                    configStorage.setAppId(a.getAppId());
                    configStorage.setSecret(a.getSecret());
                    configStorage.setToken(a.getToken());
                    configStorage.setAesKey(a.getAesKey());
                    return configStorage;
                }).collect(Collectors.toMap(WxMpDefaultConfigImpl::getAppId, a -> a, (o, n) -> o)));
        return wxMpService;
    }

    /**
     * 配置微信消息路由器，处理微信事件
     */
    @Bean
    public WxMpMessageRouter messageRouter() {
        final WxMpMessageRouter newRouter = new WxMpMessageRouter(wxMpService());
        // 记录所有事件的日志 （异步执行）
        newRouter.rule().handler(this.logHandler).next();
        // 处理关注事件
        newRouter.rule().async(false).msgType(EVENT).event(SUBSCRIBE).handler(subscribeHandler).end();
        // 取消关注事件
        newRouter.rule().async(false).msgType(EVENT).event(UNSUBSCRIBE).handler(unsubscribeHandler).end();
        return newRouter;
    }


}
